package yhao.infra.web.interceptor;


import org.springframework.validation.annotation.Validated;
import org.springframework.web.method.HandlerMethod;
import yhao.infra.common.ContextHolder;
import yhao.infra.web.common.validation.HasSpringValidationContextKey;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;

/**
 * 环境变量中增加spring校验标志
 *
 * @see yhao.infra.web.common.validation.HasSpringValidationContextKey
 * @see yhao.infra.web.common.validation.ValidationAop
 * @author yoara
 */
public class HasSpringValidationInterceptor extends ZBaseInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//仅校验方法级别的Handler
		if (!(handler instanceof HandlerMethod)) {
			return super.preHandle(request, response, handler);
		}
		if(hasValidate((HandlerMethod) handler)){
			ContextHolder.setContextData(HasSpringValidationContextKey.class,true);
		}else{
			ContextHolder.setContextData(HasSpringValidationContextKey.class,false);
		}
		return super.preHandle(request, response, handler);
	}

	private boolean hasValidate(HandlerMethod handler) {
		Annotation[][] annos = handler.getMethod().getParameterAnnotations();
		if(annos!=null){
			for(Annotation[] annotation1 : annos) {
				if(annotation1!=null){
					for(Annotation anno : annotation1) {
						if(anno instanceof Validated){
							return true;
						}
					}
				}
			}
		}
		return false;
	}
}
